package com.basic.emg.service.impl;

import com.basic.common.exception.business.BusinessException;
import com.basic.common.exception.business.ValidationException;
import com.basic.emg.domain.*;
import com.basic.emg.mapper.EmergencyMaterialMapper;
import com.basic.emg.mapper.EmergencyPlanMapper;
import com.basic.emg.mapper.EmergencyTeamMapper;
import com.basic.emg.service.EmergencyPlanService;
import com.basic.emg.utils.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import org.apache.commons.io.FilenameUtils;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 应急预案服务实现类
 */
@Service
public class EmergencyPlanServiceImpl implements EmergencyPlanService {


    @Autowired
    private EmergencyPlanMapper planMapper;
    @Autowired
    private EmergencyMaterialMapper materialMapper;
    @Autowired
    private EmergencyTeamMapper teamMapper;
    @Value("${uploadPath}")
    private String uploadPath;

    @Transactional
    @Override
    public void createPlan(EmergencyPlan plan,MultipartFile[] file) throws Exception {
        if(StringUtils.isBlank(plan.getPlanName())){
            throw new RuntimeException("预案名称不能为空");
        }
        if(StringUtils.isBlank(plan.getPlanType())){
            throw new RuntimeException("预案类型不能为空");
        }
        plan.setCreateTime(new Date());
        plan.setDelFlag("0");


        /*
        String path = null;
        if(file!=null && file.length>0){
            //上传文件
            path = FileUtil.uploadMeterImg(uploadPath+"plan", file);
            if(StringUtils.isNotBlank(path)){
                plan.setFilePath(path);
            }
        }*/
        List pathList = new ArrayList();

        if(file!=null && file.length>0){
            for(MultipartFile f : file){
                //上传文件
                String path = FileUtil.uploadMeterImg(uploadPath + "plan", f);
                if(StringUtils.isNotBlank(path)){
                    pathList.add(path);
                }
            }
            String join = StringUtils.join(pathList, ",");
            join = join.replaceAll("\\\\", "/");
            System.out.println(join);
            plan.setFilePath(join);
        }

        int i = planMapper.insertPlan(plan);

        List<EmergencyTeam> teamList = plan.getTeamList();

        if(teamList != null && !teamList.isEmpty()){
            List planTeamList = new ArrayList();
            for(EmergencyTeam team : plan.getTeamList()){
                PlanTeam planTeam = new PlanTeam(plan.getId(), team.getId());
                planTeamList.add(planTeam);
            }
            planMapper.insertPlanTeam(planTeamList);
        }

        List<EmergencyMaterial> materialList = plan.getMaterialList();

        if(materialList != null && !materialList.isEmpty()){
            List planMatList = new ArrayList();
            for(EmergencyMaterial material : plan.getMaterialList()){
                PlanMat planMat = new PlanMat(plan.getId(), material.getId());
                planMatList.add(planMat);
            }
            planMapper.insertPlanMat(planMatList);
        }


    }




    @Override
    public List<EmergencyPlan> selectPlanList(EmergencyPlan plan) {

        Example example = new Example(EmergencyPlan.class);
        Example.Criteria criteria = example.createCriteria();
        /*criteria.andEqualTo("gameType","2")
                .andEqualTo("topicId",match.getMatchId())
                .andEqualTo("status","1");
        Example.Criteria criteria2 = example.createCriteria();
        criteria2.andEqualTo("gameType","3")
                .andEqualTo("topicId",match.getMatchId())
                .andEqualTo("status","1");
        example.or(criteria2);*/
        if(StringUtils.isNotBlank(plan.getPlanName())){
            criteria.andLike("planName",'%' + plan.getPlanName() + '%');
        }
        if(StringUtils.isNotBlank(plan.getPlanType())){
            criteria.andEqualTo("planType",plan.getPlanType());
        }
        if(StringUtils.isNotBlank(plan.getPlanStatus())){
            criteria.andEqualTo("planStatus",plan.getPlanStatus());
        }
        if(plan.getStartTime1()!=null){
            criteria.andGreaterThanOrEqualTo("updateTime",plan.getStartTime1());
        }
        if(plan.getEndTime1()!=null){
            criteria.andLessThanOrEqualTo("updateTime",plan.getEndTime1());
        }
        if(plan.getStartTime2()!=null){
            criteria.andGreaterThanOrEqualTo("pubTime",plan.getStartTime2());
        }
        if(plan.getEndTime2()!=null){
            criteria.andLessThanOrEqualTo("pubTime",plan.getEndTime2());
        }
        if(plan.getPubTime()!=null){
            criteria.andEqualTo("pubTime",plan.getPubTime());
        }
        criteria.andNotEqualTo("delFlag","1");
//        matchExample.setOrderByClause("game_public_time DESC, match_date DESC ");
        List<EmergencyPlan> emergencyPlans = planMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(emergencyPlans)){
            for(EmergencyPlan pl:emergencyPlans){
                List<EmergencyTeam> teams = planMapper.selectPlanTeam(pl.getId());
                pl.setTeamList(teams);
                List<EmergencyMaterial> materialList = planMapper.selectPlanMat(pl.getId());
                pl.setMaterialList(materialList);
            }
        }

        return emergencyPlans;
    }

    @Override
    public EmergencyPlan selectPlanById(Long id) {
        if(id==null){
            throw new RuntimeException("id不能为空");
        }
        EmergencyPlan emergencyPlan = planMapper.selectByPrimaryKey(id);
        if (StringUtils.isNotBlank(emergencyPlan.getDelFlag())&&emergencyPlan.getDelFlag().equals("1")){
            return null;
        }
        List<EmergencyTeam> teams = planMapper.selectPlanTeam(emergencyPlan.getId());
        emergencyPlan.setTeamList(teams);
        List<EmergencyMaterial> materialList = planMapper.selectPlanMat(emergencyPlan.getId());
        emergencyPlan.setMaterialList(materialList);
        return emergencyPlan;
    }

    @Transactional
    @Override
    public void editPlan(EmergencyPlan plan,MultipartFile[] file) throws Exception{
        if(plan.getId()==null){
            throw new RuntimeException("id不能为空");
        }
        List pathList = new ArrayList();

        if(file!=null && file.length>0){
            for(MultipartFile f : file){
                //上传文件
                String path = FileUtil.uploadMeterImg(uploadPath + "dispose", f);
                if(StringUtils.isNotBlank(path)){
                    pathList.add(path);
                }
            }
            String join = StringUtils.join(pathList, ",");
            System.out.println(join);
            if(StringUtils.isNotBlank(plan.getFilePath())){
                String old_filePath = plan.getFilePath();
                join = old_filePath + "," + join;
                join = join.replaceAll("\\\\", "/");
            }
            plan.setFilePath(join);
        }
        plan.setUpdateTime(new Date());
        int i = planMapper.updateByPrimaryKeySelective(plan);
        if(i!=1){
            throw new RuntimeException("更新失败！");
        }
        //更新绑定队伍
        int i1 = planMapper.deletePlanTeam(plan.getId());

        //更新绑定物资
        int i2 = planMapper.deletePlanMat(plan.getId());

        List<EmergencyTeam> teamList = plan.getTeamList();

        if(teamList != null && !teamList.isEmpty()){
            List planTeamList = new ArrayList();
            for(EmergencyTeam team : plan.getTeamList()){
                PlanTeam planTeam = new PlanTeam(plan.getId(), team.getId());
                planTeamList.add(planTeam);
            }
            planMapper.insertPlanTeam(planTeamList);
        }

        List<EmergencyMaterial> materialList = plan.getMaterialList();

        if(materialList != null && !materialList.isEmpty()){
            List planMatList = new ArrayList();
            for(EmergencyMaterial material : plan.getMaterialList()){
                PlanMat planMat = new PlanMat(plan.getId(), material.getId());
                planMatList.add(planMat);
            }
            planMapper.insertPlanMat(planMatList);
        }

    }

    @Transactional
    @Override
    public void deletePlan(List<Long> ids) {

        if(CollectionUtils.isEmpty(ids)){
            throw new RuntimeException("id不能为空");
        }
        for(Long id : ids){
            EmergencyPlan plan = new EmergencyPlan();
            plan.setId(id);
            plan.setDelFlag("1");
            planMapper.updateByPrimaryKeySelective(plan);
            //int i = planMapper.deleteByPrimaryKey(id);

        }

    }
}
